<template>
  <div class="app-container">
    <el-form :inline="true">
      <div style="display: flex; justify-content: space-between;">
        <div>
          <el-form-item>
            <el-input v-model="key" clearable placeholder="请输入查询内容" style="width: 200px;" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="uid" clearable placeholder="用户ID" style="width: 200px;" />
          </el-form-item>
          <el-form-item>
            <el-select v-model="coinid" placeholder="币种">
              <el-option label="全部" :value="0" />
              <el-option v-for="item in coinList" :disabled="item.coinid == 3" :label="item.coinname"
                :value="item.coinid" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="state" placeholder="请选择">
              <el-option key="-1" label="全部" :value="-1" />
              <el-option key="0" label="待审核" :value="0" />
              <el-option key="1" label="已打款" :value="1" />
              <el-option key="2" label="已驳回" :value="2" />
              <el-option key="3" label="已审核待处理" :value="3" />
              <el-option key="4" label="打款失败" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="dateTime" type="daterange" range-separator="至" value-format="yyyy-MM-dd"
              start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="init">查询</el-button>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item>
            <el-button type="primary" :loading="exportLoading" @click="doExport">导出Excel</el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <!-- 列表 -->
    <el-table v-loading="listLoading" :data="tableData" style="margin-top: 10px" element-loading-text="Loading" border
      fit highlight-current-row>
      <el-table-column prop="userId" label="用户ID" width="80" align="center" />
      <el-table-column prop="fromUserName" label="用户账号" width="80" align="center" />
      <el-table-column prop="coinid" label="提现币种" width="90" align="center">
        <template slot-scope="{row}">
          <span v-if="row.coinid == item.coinid" v-for="item in coinList">{{ item.coinname }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="applyAmount" label="提现金额" width="90" align="center">

        <template slot-scope="{row}">
          <span>{{ row.applyAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="fee" label="手续费" width="90" align="center" />
      <el-table-column prop="toAmount" label="实际到账" width="90" align="center" />
      <el-table-column prop="fromAddr" label="来源地址" align="center" />
      <el-table-column prop="toAddr" label="收款地址" align="center" />
      <el-table-column prop="alipayaccount" label="支付宝收款账号" align="center" />
      <el-table-column prop="state" label="状态" align="center">
        <template slot-scope="{row}">
          <el-tag>{{ row.state_str }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="etime" label="审核时间" align="center" />
      <el-table-column prop="tradehash" label="交易哈希" align="center" />
      <el-table-column prop="remark" label="状态变迁说明" align="center" />
      <el-table-column prop="etime" label="申请时间" align="center">

        <template slot-scope="{row}">
          <span>{{ row.etime }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="操作" fixed="right" width="120" align="center">

        <template v-if="row.state == 0" slot-scope="{row}">
          <el-button size="mini" type="primary" @click="onVisible(row)">审核</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block " style="padding-top: 20px;">
      <el-pagination background :current-page="PageIndex" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="totalCount" @size-change="idx => { pageSize = idx }"
        @current-change="idx => { PageIndex = idx }" />
    </div>

    <!-- 审核对话框 -->
    <el-dialog title="提现审核" :visible="dialogVisible" width="600px" :modal-append-to-body="false" @close="handleClose">
      <el-form ref="form" :model="form" :rules="rulesModel" class="form" label-width="130px">
        <el-form-item label="审核状态" prop="state">
          <el-select v-model="form.state" style="width: 150px;" @change="e => { form.remark = '' }">
            <el-option label="已打款" value="1" />
            <el-option label="审核通过" value="4" />
            <el-option label="驳回" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易哈希" prop="remark" v-if="form.state == 1">
          <el-input v-model="form.remark" placeholder="请输入交易哈希" />
        </el-form-item>
        <el-form-item label="驳回理由" prop="remark" v-if="form.state == 2">
          <el-input v-model="form.remark" placeholder="请输入驳回理由" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="onEdit">确定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { mapState } from 'vuex'
import { tradetransactionout, tradetransferExcel, setoutstate } from '@/api/users.js'
import { GetEnum, coinlist } from "@/api/ctrls.js";
import { formatDate } from '@/utils/index.js'
export default {
  name: 'Permission',
  data() {
    return {
      // 筛选参数
      key: '',
      state: -1,
      uid: '', // 用户id
      coinid: 0,// 币种id
      dateTime: [0, 0], // 时间查询

      coinList: [],// 币种列表
      WithdrawState: {}, // 提现状态实体

      // 列表相关
      tableData: [],
      totalCount: 0,
      PageIndex: 1,
      pageSize: 10,
      listLoading: false,
      total: {},

      // 审核对话框相关
      dialogVisible: false,
      editLoading: false,
      form: {},
      currentInfo: 0, // 选中实体
      rulesModel: {
        state: [
          { required: true, message: '请选择审核状态', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入驳回原因', trigger: 'blur' }
        ]
      },

      exportLoading: false, // 导出loading
    }
  },
  computed: {
    ...mapState({
      enumList: state => state.user.enumList,
    }),
  },
  watch: {
    PageIndex(val) {
      this.getTableList()
    },
    pageSize(val) {
      this.getTableList()
    }
  },
  created() {
    const time = parseInt(Date.now() / 1000)
    this.dateTime[0] = formatDate(new Date((time - 10 * 24 * 60 * 60) * 1000), 'yyyy-MM-dd')
    this.dateTime[1] = formatDate(new Date(), 'yyyy-MM-dd')
  },
  async mounted() {
    this.uid = this.$route.query.userid || ''
    const tim = this.$route.query.time || ''
    if (tim == 'day') {
      this.dateTime = [formatDate(new Date(), 'yyyy-MM-dd'), formatDate(new Date(), 'yyyy-MM-dd')]
    }
    this.GetEnum();
    this.GetCoin();
    await this.getTableList()
  },
  methods: {
    /**列表刷新加载 */
    init() {
      this.PageIndex = 1;
      this.getTableList()
    },
    //////////////////////////////////////////// 导出/导入 /////////////////////////////////////////////
    // 导出报表
    async doExport(name) {
      this.exportLoading = true
      const res = await tradetransferExcel({
        key: this.key,
        state: this.state,
        stime: this.dateTime ? this.dateTime[0] : '',
        etime: this.dateTime ? this.dateTime[1] : '',
      })
      this.exportLoading = false
      if (res) {
        const link = document.createElement('a')
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        let num = ''
        for (let i = 0; i < 10; i++) {
          num += Math.ceil(Math.random() * 10)
        }
        link.setAttribute('download', this.dateTime[0] + '-' + this.dateTime[1] + '提现申请列表.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }
    },
    // 导入上传前
    quillImgBefore(file) {
      const fileName = file.name
      const reg = /\.(xlsx|xls|csv)$/
      if (reg.test(fileName)) {
        return true
      } else {
        this.$message.error('请插入以.xlsx/.xls/.csv结尾的文件')
        return false
      }
    },
    /**导入 */
    importExport(file) {
      this.$AliExcelImp(file, ({ msg, success }) => {
        this.$message({
          message: msg,
          type: success ? 'success' : 'error'
        })
        this.init();
      })
    },
    //////////////////////////////////////////// 审核对话框 /////////////////////////////////////////////
    /**对话框打开前（操作审核） */
    onVisible(row, type) {
      // 先初始化
      this.currentInfo = row
      this.form = {
        id: row.id,
        state: '',
        remark: ''
      }
      this.dialogVisible = true
    },
    /**审核提交 */
    async onEdit() {
      try {
        await this.$refs['form'].validate()
      } catch (e) {
        console.log(e)
        return
      }
      this.editLoading = true;
      const { success, msg } = await setoutstate(this.form);
      this.editLoading = false;
      if (success) {
        this.dialogVisible = false
        this.init()
      }
      this.$message({
        message: msg,
        type: success ? 'success' : 'error'
      })
    },
    /**对话框关闭前 */
    handleClose() {
      this.$refs.form.resetFields()
      this.$refs.form.clearValidate()
      this.dialogVisible = false
    },
    //////////////////////////////////////////// 数据请求 /////////////////////////////////////////////
    /**主列表 */
    async getTableList() {
      this.listLoading = true
      const { list, totalCount, total } = await tradetransactionout({
        key: this.key,
        state: this.state,
        uid: this.uid,
        coinid: this.coinid,
        stime: this.dateTime ? this.dateTime[0] : '',
        etime: this.dateTime ? this.dateTime[1] : '',
        PageIndex: this.PageIndex,
        PageSize: this.pageSize
      })

      this.totalCount = totalCount
      list.forEach(element => {
        element.ctime = element.ctime.replace('T', ' ')
        element.etime = element.etime.replace('T', ' ')
        // element.applyamount = element.applyamount % 1 === 0 ? element.applyamount : element.applyamount.toFixed(2)
        // element.amount = element.amount % 1 === 0 ? element.amount : element.amount.toFixed(2)
        this.tableData.push(element)
      })
      this.tableData = list
      this.listLoading = false
    },
    // 获取枚举
    async GetEnum() {
      const res = await GetEnum();
      this.WithdrawState = res.data['WithdrawState'];
    },
    // 获取币种
    async GetCoin() {
      const res = await coinlist();
      this.coinList = res;
    },
  }
}
</script>

<style lang="scss" scoped>
.form-inline {
  padding: 0;
}

.audit-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

<style lang="scss">
.el-dialog {
  .el-tag {
    height: auto;
    white-space: initial;
    margin-bottom: 5px;
    margin-right: 5px;
  }

  .el-card__body {
    max-height: 400px;
    overflow-y: scroll;
  }
}
</style>
